#include "ctaskservice.h"

//构造函数
CTaskService::CTaskService(forwardParaSt *&para, QObject *parent) :
    m_forwardPara(para),QObject(parent)
{
    m_clientId = 0;
    m_TcpServer = new QTcpServer;
    m_checkTimer = new QTimer;
    m_printDataFlag = true;

    connect(m_checkTimer,&QTimer::timeout, this, &CTaskService::checkTask);
    connect(m_TcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnect()));
}

//析构函数
CTaskService::~CTaskService()
{
    stopService();
    delete m_TcpServer;
}

//停止所有任务
void CTaskService::stopAllClient()
{
    QMap<int, CTaskProc*>::iterator iter;
    for(iter = m_taskMap.begin(); iter != m_taskMap.end(); iter++)
    {
        emit removeClient(m_forwardPara->listenPort,iter.value()->getId());
        iter.value()->stop();
        delete iter.value();
    }
    m_taskMap.clear();
}

//接收新连接，创建转发任务
void CTaskService::acceptConnect()
{
    QTcpSocket*  tcpSocket;
    tcpSocket = m_TcpServer->nextPendingConnection();

    CTaskProc *pTask = new CTaskProc(m_clientId,tcpSocket, m_forwardPara->toIp,m_forwardPara->toPort);
    connect(pTask,&CTaskProc::sigTaskEnd,this,&CTaskService::onProcTaskEnd);
    connect(pTask,&CTaskProc::sigReadLocalClientData,this,&CTaskService::onRecvLocalClientData);
    connect(pTask,&CTaskProc::sigReadSvrClientData,this,&CTaskService::onRecvSvrClientData);
    connect(pTask,&CTaskProc::sigTaskStartOk,this,&CTaskService::onProcTaskStartOk);

    qDebug()<<"add new client now "<<m_clientId<<", row: "<<m_forwardPara->itemProject->row()<<m_forwardPara->itemProject->rowCount();

    m_taskMap[m_clientId] = pTask; //add to task map

    qDebug()<<QString("%1 : 接收到客户端连接, id=%2").arg(m_forwardPara->listenPort).arg(m_clientId);
    disMsg(QString("%1 : 接收到客户端连接, id=%2").arg(m_forwardPara->listenPort).arg(m_clientId));
    m_clientId++;
}

//启动服务
void CTaskService::startService()
{
    if(!m_TcpServer->listen(QHostAddress::Any,m_forwardPara->listenPort))
    {
      disMsg(m_TcpServer->errorString());
      m_TcpServer->close();
      return;
    }

    m_checkTimer->start(10000);
}

//停止服务
void CTaskService::stopService()
{
    stopAllClient();
    m_checkTimer->stop();
    m_TcpServer->close();
    m_clientId = 0;
}

//用于向UI界面发送要显示的错误信息!
void CTaskService::disMsg(QString str)
{
    emit sendErrorMsg(str);
}

//转发任务启动成功
void CTaskService::onProcTaskStartOk(int id)
{
    emit addClient(m_forwardPara->listenPort, id);
}

//任务终止信号处理
void CTaskService::onProcTaskEnd(int id)
{
    qDebug()<<QString("port[%1] client[id:%2] disconnect!").arg(m_forwardPara->listenPort).arg(id);
    m_taskMap.remove(id);

    emit removeClient(m_forwardPara->listenPort,id);
}

//接收客户端的数据
void CTaskService::onRecvLocalClientData(int id, QByteArray &data)
{
    if ( !m_printDataFlag )
        return;

//    if ( id == m_printDataId)
        emit sendLocalClientData(id, data);
}

//接收服务端的数据
void CTaskService::onRecvSvrClientData(int id, QByteArray &data)
{
    if ( !m_printDataFlag )
        return;
    qDebug()<<"id: "<<id<<", recv data: "<<data.length();
//    if ( id == m_printDataId)
        emit sendSvrClientData(id, data); //发给界面用于显示
}

void CTaskService::setSelectId(int id)
{
    qDebug()<<"set select id: "<<id;
    m_printDataFlag = true;
    m_printDataId = id;
}

void CTaskService::stopPrintData()
{
//    m_printDataFlag = false;
}

//任务定时检测，用于定时检测是否由终止的任务，如果有，则释放
void CTaskService::checkTask()
{
    QMap<int, CTaskProc*>::iterator iter ;
    for ( iter = m_taskMap.begin(); iter != m_taskMap.end(); iter)
    {
        if(iter.value()->isValid())
        {
            qDebug()<<m_forwardPara->listenPort<<",id: "<<iter.key()<<", valid";
            iter++;
            continue;
        }

        qDebug()<<m_forwardPara->listenPort<<",id: "<<iter.key()<<", invalid, remove";
        delete iter.value();
        m_taskMap.erase(iter++);
    }
}

//发给svr的数据
void CTaskService::onSendToServer(int id, QByteArray data)
{
    auto iter = m_taskMap.find(id);
    if ( iter != m_taskMap.end() )
        iter.value()->sendToServer(data);
}

//发给dev的数据
void CTaskService::onSendToDevice(int id, QByteArray data)
{
    auto iter = m_taskMap.find(id);
    if ( iter != m_taskMap.end() )
        m_taskMap[id]->sendToDevice(data);
}
